<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;
use Workerman\Timer;

require_once 'mysql-master/src/Connection.php';
require_once "service/Stock.php";
require_once "service/User.php";

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    public static $allowAccessPostion = [
        'index_hots'    => ['page'=>'首页','interval'=>2],
        'index_asset'   => ['page'=>'首页资产信息','interval'=>2],
        'trade_index'   => ['page'=>'交易首页','interval'=>2],
        'trade_hold_shares' => ['page'=>'交易持仓列表','interval'=>2],
        'asset'         => ['page'=>'资产页面信息','interval'=>2],
        'stockinfo'     => ['page'=>'交易-股票详情','interval'=>2],
        'admin_login'   => ['page'=>'后台登陆'],
        'register_ok'   => ['page'=>'前台开户跟进提醒'],
        
    ];


    /**
     * 当businessWorker进程启动时触发。每个进程生命周期内都只会触发一次
     * 做一些全局初始化工作
     */
    public static function onWorkerStart($businessWorker)
    {
        global $db,$redis;
    
        $config = include(__DIR__ . '/config.php');

        $db = new \Workerman\MySQL\Connection(
            $config['db']['host'],
            $config['db']['port'],
            $config['db']['user'],
            $config['db']['password'],
            $config['db']['dbname'],
            $config['db']['charset']
        );

        $redis = new \Redis();
        $redis->connect($config['redis']['host'], $config['redis']['port']);
        $redis->auth($config['redis']['auth']);
    }

    /**
     * 当客户端连接时触发
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        Gateway::joinGroup($client_id, 'allOnline');
    }

    /**
     * 当客户端连接上gateway完成websocket握手时触发的回调函数
     */
    public static function onWebSocketConnect($client_id, $data)
    {
        if (!isset($data['get']['type'])) {
             Gateway::closeClient($client_id);
        }

        $postion = strtolower($data['get']['type']);
        if( array_key_exists($postion,self::$allowAccessPostion) == false){
            Gateway::sendToClient($client_id, '无效的请求');
            Gateway::closeClient($client_id);
       }
        // 通过全局变量获得db、redis实例
        global $db,$redis;
        // 定时器执行间隔
        $interval = self::$allowAccessPostion[$postion]['interval'] ?? 3;
        switch ($postion) 
        {
           // 首页热点
           case 'index_hots':
               $stockObj = new Stock($db,$redis);
               $_SESSION[$client_id] = Timer::add($interval, function() use($client_id,$stockObj){
                   $codeList = $stockObj->getHotSearchList();
                   Gateway::sendToClient($client_id, json_encode($codeList,JSON_UNESCAPED_UNICODE));
               });
           break;
           // 单只股票信息
           case 'stockinfo':
                if (!isset($data['get']['token'])) {
                        Gateway::closeClient($client_id);
                }
                $all_no = $data['get']['all_no'];
                $stockObj = new Stock($db,$redis);
                $_SESSION[$client_id] = Timer::add($interval, function() use($client_id,$stockObj,$all_no){
                    $codeList = $stockObj->getStockInfo($all_no);
                    Gateway::sendToClient($client_id, json_encode($codeList,JSON_UNESCAPED_UNICODE));
                });
            break;
           // 我的资产
           case 'asset':
                if (!isset($data['get']['token'])) {
                        Gateway::closeClient($client_id);
                }
                $token = $data['get']['token'];
                $userObj = new User($token,$redis,$db);
                $_SESSION[$client_id] = Timer::add($interval, function() use($client_id,$userObj){
                   $codeList = $userObj->getAsset();
                   Gateway::sendToClient($client_id, json_encode($codeList,JSON_UNESCAPED_UNICODE));
                });
           break;
           // 首页资产信息
           case 'index_asset':
                if (!isset($data['get']['token'])) {
                        Gateway::closeClient($client_id);
                }
                $token = $data['get']['token'];
                $userObj = new User($token,$redis,$db);
                $_SESSION[$client_id] = Timer::add($interval, function() use($client_id,$userObj){
                    $codeList = $userObj->getIndexAssets();
                    Gateway::sendToClient($client_id, json_encode($codeList,JSON_UNESCAPED_UNICODE));
                });
        break;
           // 交易首页
           case 'trade_index':
                    if (!isset($data['get']['token'])) {
                        Gateway::closeClient($client_id);
                    }
                    $token = $data['get']['token'];
                    $userObj = new User($token,$redis,$db);
                    $_SESSION[$client_id] = Timer::add($interval, function() use($client_id,$userObj){
                        $codeList = $userObj->positionStatistics();
                        Gateway::sendToClient($client_id, json_encode($codeList,JSON_UNESCAPED_UNICODE));
                    });
            break;
            // 交易持仓
           case 'trade_hold_shares':
                    if (!isset($data['get']['token'])) {
                        Gateway::closeClient($client_id);
                    }
                    $token = $data['get']['token'];
                    
                    if( isset($data['get']['all_no']) && strlen($data['get']['all_no']) == 8 ){
                        $allNo = $data['get']['all_no'];
                    }else{
                        $allNo = '';
                    }
                    $userObj = new User($token,$redis,$db);
                    $_SESSION[$client_id] = Timer::add($interval, function() use($client_id,$userObj,$allNo){
                        $codeList = $userObj->getUserHoldStockDetails($allNo);
                        Gateway::sendToClient($client_id, json_encode($codeList,JSON_UNESCAPED_UNICODE));
                    });
            break;
           // 后台管理员成功
           case 'admin_login':
                Gateway::joinGroup($client_id, 'admin_online');
           break;
           // 前台开户成功
           case 'register_ok':
                if (!isset($data['get']['token'])) {
                    Gateway::closeClient($client_id);
                }
                $token = $data['get']['token'];
                $userObj = new User($token,$redis,$db);
                if( $userObj->getUserInfo() ){
                    Gateway::sendToGroup('admin_online', '有新会员开户成功,请及时跟进');
                }
                Gateway::closeClient($client_id);
           break;
           
           default:
               break;
        }
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息['type'=>'index']
    */
   public static function onMessage($client_id, $message)
   {
        $arrMessage = json_decode($message,true);
       
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       // 向所有人发送 
       //GateWay::sendToAll("$client_id logout\r\n");
       if(isset($_SESSION[$client_id])){
        Timer::del($_SESSION[$client_id]);
       }
       
   }
}
